// #ifdef H5
const BASE_URL = "/api";
// #endif
// #ifdef MP-WEIXIN
const BASE_URL = "https://apizx01.sc798.com";
// #endif

// 请求拦截器
const requestInterceptor = (config) => {
  // 添加token等认证信息
  const token = uni.getStorageSync("token");
  if (token) {
    config.header = config.header || {};
    config.header["Authorization"] = `Bearer ${token}`;
  }

  // 显示加载提示
  if (config.showLoading) {
    uni.showLoading({
      title: "加载中...",
      mask: true,
    });
  }

  return config;
};

// 响应拦截器
const responseInterceptor = (response, config) => {
  // 隐藏加载提示
  if (config.showLoading) {
    uni.hideLoading();
  }

  const { statusCode, data } = response;
  if (statusCode === 200) {
    // 根据后端返回的数据结构进行调整
    if (data && data.code == 200) {
      return data;
    } else {
      // 业务错误
      const errorMsg = data.message || "请求失败";
      if (config.showError) {
        uni.showToast({
          title: errorMsg,
          icon: "none",
          duration: 2000,
        });
      }
      return Promise.reject(new Error(errorMsg));
    }
  } else {
    // HTTP错误
    const errorMsg = `请求失败: ${statusCode}`;
    if (config.showError) {
      uni.showToast({
        title: errorMsg,
        icon: "none",
        duration: 2000,
      });
    }
    return Promise.reject(new Error(errorMsg));
  }
};

// 错误处理
const errorHandler = (error, config) => {
  // 隐藏加载提示
  if (config.showLoading) {
    uni.hideLoading();
  }

  let errorMessage = "网络请求失败";

  if (error.errMsg) {
    if (error.errMsg.includes("request:fail")) {
      errorMessage = "网络连接失败，请检查网络设置";
    }
  }

  if (config.showError) {
    uni.showToast({
      title: errorMessage,
      icon: "none",
      duration: 2000,
    });
  }

  return Promise.reject(error);
};

// 核心请求方法
export const request = (options) => {
  // 合并配置
  const config = {
    url: "",
    method: "GET",
    data: {},
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    timeout: 10000,
    showLoading: true,
    showError: true,
    ...options,
  };

  // 处理完整URL(检查是否是以http开头的请求url)
  if (!config.url.startsWith("http")) {
    config.url = BASE_URL + config.url;
  }

  // 请求拦截
  const finalConfig = requestInterceptor(config);

  return new Promise((resolve, reject) => {
    uni.request({
      url: finalConfig.url,
      method: finalConfig.method,
      data: finalConfig.data,
      header: finalConfig.header,
      timeout: finalConfig.timeout,
      success: (response) => {
        try {
          const result = responseInterceptor(response, finalConfig);
          resolve(result);
        } catch (error) {
          reject(error);
        }
      },
      fail: (error) => {
        errorHandler(error, finalConfig).catch(reject);
      },
    });
  });
};
